package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.management.mapper.RoleMapper;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.util.JwtUtil;
import com.qk.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFIX = "123";

    /**
     * 条件分页查询用户列表
     */
    @Override
    public PageResult<UserDO> getUsers(UserDTO userDto) {
        // 开始分页
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());

        // 执行查询
        List<UserDO> users = userMapper.getUsers(userDto);

        // 获取分页信息
        Page<UserDO> pageInfo = (Page<UserDO>) users;

        // 封装成 PageResult 对象
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }

    @Override
    public void addUser(User user) {
        // 参数校验： 工具类处理 hutool 工具类
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime","deptName","roleName");
        System.out.println(hasNull);
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 设置默认密码
        // 原始密码（明文密码）
        String rawPassword = user.getUsername()+DEFAULT_PASSWORD_SUFIX;
        // MD5算法对原始密码进行消息摘要处理得到字符串（密文密码）
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        // 插入
        userMapper.insert(user);
    }

    @Override
    public void deleteUsers(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        // 设置更新时间为当前时间
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密处理
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword() + "123").getBytes()));
        userMapper.update(user);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        // 1. 参数合法性校验
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 2. 根据用户名查询数据库获取用户对象
        User dbUser = userMapper.selectByUsername(dto.getUsername());
        // 3. 数据合法性校验
        if (Objects.isNull(dbUser)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        // 4. 密码校验
        // 4.1获取前端用户传递密码,对其进行MD5
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String encodedPassword = dbUser.getPassword();
        boolean isChecked = ObjectUtil.equals(userPassword, encodedPassword);
        if (!isChecked){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        // 5. 数据封装返回
        // 5.1 根据角色id查询角色信息 【 角色标签 方式1 多表关联查询  方式2 根据角色id查询角色表】
        Role role = roleMapper.selectById(dbUser.getRoleId());
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                // TODO token 未处理
                .token(JwtUtil.generateToken(claims))
                .build();
    }

    @Override
    public List<User> listAllUsers() {
        return userMapper.listAllUsers();
    }

    @Override
    public List<User> getUsersByRoleLabel(String roleLabel) {
        return userMapper.getUsersByRoleLabel(roleLabel);
    }

    @Override
    public List<User> getUsersByDeptId(Integer deptId) {
        return userMapper.getUsersByDeptId(deptId);
    }
}